package com.yunhe.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.acl.Owner;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.constant.CarStatic;
import com.yunhe.entity.CarDevice;
import com.yunhe.entity.CarOwner;
import com.yunhe.entity.CarPic;
import com.yunhe.entity.CarPrice;
import com.yunhe.entity.Cars;
import com.yunhe.entity.Clientuser;
import com.yunhe.service.CarsService;

/**
 * 分享爱车
 * 
 * @author 冯振鑫
 * @version 1.0.0
 * @da2017年5月23日 上午9:53:42
 */
@Controller
public class ShareCar {

	@Autowired
	@Qualifier(value = "CarsService")
	private CarsService carsService;

	/*
	 * @InitBinder public void initBinder(WebDataBinder binder){
	 * SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	 * dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new
	 * CustomDateEditor(dateFormat, true)); }
	 */

	/**
	 * 冯振兴 跳转到新车入册爱车界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/NewCarAddUI.html")
	public String NewCarAddUI() {
		System.out.println("跳转到NewCarAddUI页面");
		return "NewCarAddUI";
	}

	/**
	 * 新车入册 冯振兴
	 * 
	 * @param cars
	 *            汽车
	 * @param clientuser
	 *            客户信息
	 * @param model
	 * @return 重定向到列表页面
	 */
	@RequestMapping(value = "/NewCarAdd.html", method = RequestMethod.POST)
	@ResponseBody
	public String NewCarAdd(Cars cars,  Clientuser clientuser, 
			HttpServletRequest request) {
		
		//汽车 
		cars.setAddtime(new Date()); //设置入册时间
		String carid = UUID.randomUUID().toString();
		cars.setCarid(carid); 	//设置主键
	
		
		
		//客户信息表
		String clientid=UUID.randomUUID().toString();
		clientuser.setUid(clientid);
		clientuser.setAddtime(new Date());
	
		//车辆车主关系
		CarOwner carOwner=new CarOwner();
		carOwner.setCarid(carid);
		carOwner.setClientid(clientid);
		carOwner.setAddtime(new Date());
		
		//设置图片关系
			//插入图片
				//获取图片路径
				HttpSession session = request.getSession();
				ArrayList<String> attribute = (ArrayList<String>) session.getAttribute("pathList");
				if(attribute!=null){
				
					//清除session中地方数据
					session.removeAttribute("pathList");
				}

				carsService.carBooked(cars, carOwner, attribute, clientuser);
				
				 return "-1"; 
		

	}
	
	@RequestMapping(value="/vinQuery/{vin}",method=RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public  String vinQuery(@PathVariable String vin ) throws Exception{
	
		String url="http://route.showapi.com/1142-1?showapi_appid=39784&vin="+vin+"&showapi_sign=1262321cdece476ea3611d49fa037e93";
	/*	
		System.out.println(url);
		URL u=new URL(url);
        InputStream in=u.openStream();
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        try {
            byte buf[]=new byte[1024];
            int read = 0;
            while ((read = in.read(buf)) > 0) {
                out.write(buf, 0, read);
            }
        }  finally {
            if (in != null) {
                in.close();
            }
        }
        byte b[]=out.toByteArray( );
      
        String s=new String(b,"utf-8");
        System.out.println(s);*/
		String s="{\"showapi_res_code\": 0,\"showapi_res_error\": \"\",\"showapi_res_body\": {\"assembly_factory\": \"\",\"sale_name\": \"1.6 手自一体 时尚版\",\"engine_type\": \"BWH\",\"brand_name\": \"大众\",\"model_name\": \"宝来\",\"car_type\": \"轿车\",\"ret_code\": 0,\"vin\": \"lfv2a2150a3043256\",\"power\": \"74\",\"jet_type\": \"\",\"fuel_Type\": \"汽油\",\"transmission_type\": \"手自一体变速器(AMT)\",\"cylinder_number\": \"4\",\"drive_style\": \"前轮驱动\",\"made_year\": \"2010\",\"output_volume\": \"1.6\",\"air_bag\": \"\",\"cylinder_form\": \"\",\"seat_num\": \"5\",\"vehicle_level\": \"紧凑型车\",\"door_num\": \"四门\",\"car_body\": \"三厢\",\"manufacturer\": \"一汽大众\",\"gears_num\": \"6\",\"car_weight\": \"1335\"}}";
		

        //String s ="{'showapi_res_code':0,'showapi_res_error':'','showapi_res_body':{'assembly_factory':'','sale_name':'1.6 手自一体 时尚版','engine_type':'BWH','brand_name':'大众','model_name':'宝来','car_type':'轿车','ret_code':0,'vin':'lfv2a2150a3043256','power':'74','jet_type':'','fuel_Type':'汽油','transmission_type':'手自一体变速器(AMT)','cylinder_number':'4','drive_style':'前轮驱动','made_year':'2010','output_volume':'1.6','air_bag':'','cylinder_form':'','seat_num':'5','vehicle_level':'紧凑型车','door_num':'四门','car_body':'三厢','manufacturer':'一汽大众','gears_num':'6','car_weight':'1335'}}";
        return s;
		
	
		
	}
	
	
	
	/**
	 * 文件上传
	 */

	ArrayList<String> pathList = new ArrayList<String>();

	@RequestMapping(value = "/uploadPicture.html")
	@ResponseBody
	public void uploads(@RequestParam("file") MultipartFile[] files,
			String destDir, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException,
			IOException {
		// 用与保存上传文件的路径
		System.out.println("111111111111");

		HttpSession session = request.getSession();

		for (MultipartFile multipartFile : files) {
			String originalFilename = multipartFile.getOriginalFilename();

			// 上传图图片
			if (originalFilename != null && originalFilename.length() > 0) {
				// 存储图片的物理路径
				String pic_path = "E:\\upload";
				// 新的图片名称
				String newFileName = UUID.randomUUID()
						+ originalFilename.substring(originalFilename
								.lastIndexOf("."));
				// 新图片
				File newFile = new File(pic_path, newFileName);
				// 将内存中的数据写入磁盘
				multipartFile.transferTo(newFile);
				// 得到真实路径和名字 放入集合中
				pathList.add(newFile.getAbsolutePath());
			}
		}
		// 把集合放入session中
		session.setAttribute("pathList", pathList);

	}

	
	/**
	 * 跳入审核列表界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/newsCarListUI.html", method = RequestMethod.GET)
	public String newsCarListUI() {
		return "NewCarListShenhe";
	}

	
	/**
	 * 跳入上架列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/newsCarListUIShangjia.html", method = RequestMethod.GET)
	public String newsCarListUIShangjia() {

		return "NewCarListShangjia";

	}

	/**
	 * 新车审核列表
	 * 
	 * @param carcode
	 *            车牌号
	 * @param mobile
	 *            电话号
	 * @param carstatic
	 *            车辆状态 
	 * @param draw
	 *            【jquery datatable特有的固定参数：第几次点击查询】
	 * @param start
	 *            【jquery datatable特有的固定参数：从第几条数据开始查询】
	 * @param length
	 *            【jquery datatable特有的固定参数：每页多少条数据】
	 * @return
	 */
	@RequestMapping(value = "/CarList")
	public @ResponseBody
	Map<String, Object> newsCarList(
			@RequestParam(required = false) String carcode,
			@RequestParam(required = false) String mobile,
			@RequestParam(required = false) String carstatic,
			@RequestParam int draw, @RequestParam int start,
			@RequestParam int length) {
		Map<String, Object> conditions = new HashMap<String, Object>();
		// 封装条件
		conditions.put("carcode", carcode);
		conditions.put("mobile", mobile);
		conditions.put("carstatic", carstatic);

		// 设置分页
		int pageNum = (start / length) + 1;// 当前查询的第几页
		int pageSize = length;
		PageHelper.startPage(pageNum, pageSize);
		
		// 调用 查询
		List<Map> listCarBymobileCarcodeCarStatic = carsService
				.listCarBymobileCarcodeCarStatic(conditions);
		
		PageInfo<Map> pageInfo = new PageInfo<Map>(
				listCarBymobileCarcodeCarStatic);
		// 创建 用来返回到map
		Map<String, Object> resultMap = new HashMap<String, Object>();

		/*
		 * draw: 表示请求次数
		 * 
		 * recordsTotal: 总记录数
		 * 
		 * recordsFiltered: 过滤后的总记录数
		 * 
		 * data: 具体的数据对象数组
		 */

		resultMap.put("draw", draw);
		resultMap.put("recordsTotal", pageInfo.getTotal());
		resultMap.put("recordsFiltered", pageInfo.getTotal());
		resultMap.put("data", pageInfo.getList());
		List<Map> list = pageInfo.getList();
	
		
		for (Map map : list) {
			System.out.println(map.get("carcode"));
		}
		return resultMap;
	}

	
	/**
	 * 审核页面
	 * @param carid
	 * @return
	 */
	@RequestMapping(value = "/newsCarAuditUI.html")
	public ModelAndView newsCarAuditUI(
			@RequestParam(required = true) String carid) {

		Map<String, Object> selectCarAndUserByCarId = carsService
				.selectCarAndUserByCarId(carid);

		Map<String, Object> carMap = new HashMap<String, Object>();
		carMap.put("car", selectCarAndUserByCarId);
		return new ModelAndView("newCar_shenhe", carMap);

	}

	/**
	 * 上架页面
	 * 
	 * @param carid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/newsCarShowUI.html")
	public String newsCarShowUI(@RequestParam(required = true) String carid,
			Model model) {

		Map<String, Object> selectCarAndUserByCarId = carsService
				.selectCarAndUserByCarId(carid);
		model.addAttribute("car", selectCarAndUserByCarId);

		return "newCar_shangjia";
	}

	/**
	 * 审核
	 * 
	 * @param carService
	 */
	@RequestMapping(value = "/carAuditOk.html", method=RequestMethod.POST)
	@ResponseBody
	public String carAudit( Cars cars) {
		System.out.println(cars);
		// 设置状态为审核通过
		carsService.carAudit(cars);
		return "1";
		
	}

	/**
	 * 上架AND下架AND	报废
	 * 
	 * @param carid
	 * @param dayprice
	 *            日租价格
	 * @param tempmoney
	 *            车辆押金
	 * @param rulemoney
	 *            违章押金
	 * @param basicinsure
	 *            基本保险
	 * @param deviceid
	 *            超时费用
	 * @param simcard
	 *            sim卡
	 * @param timeoutmoney
	 *            超时费用
	 * @param ownermoney
	 *            车主提成
	 * @param discount
	 *            是否有折扣
	 * @param carstate
	 *            汽车状态
	 * @return
	 */

	@RequestMapping(value = "/carShow.html" ,method=RequestMethod.POST)
	@ResponseBody
	public String carShow(
			@RequestParam(required = true) String carid,
			@RequestParam(required = false) String dayprice,
			@RequestParam(required = false) String tempmoney,
			@RequestParam(required = false) String rulemoney,
			@RequestParam(required = false) String basicinsure,
			@RequestParam(required = false) String deviceid,
			@RequestParam(required = false) String simcard,
			@RequestParam(required = false) String timeoutmoney,
			@RequestParam(required = false) String ownermoney,
			@RequestParam(required = false) String discount,
			@RequestParam(required = false) int carstate) {

		
		//设置汽车状态
		Cars cars=new  Cars();
		//设置车辆价格
		CarPrice carPrice=new CarPrice();
		CarDevice carDevice=new CarDevice();
		
		if(carstate==6){
			cars.setCarid(carid);
			cars.setCarstate(carstate);
			
			carPrice.setCarid(carid);//汽车id
			carPrice.setAddtime(new Date());//添加时间
			carPrice.setDayprice(new Double(dayprice));//日租价格
			carPrice.setTempmoney(new Double(tempmoney));//车辆押金
			carPrice.setRulemoney(new Double(rulemoney));//违章押金
			carPrice.setBasicinsure(new Double(basicinsure));//基本保险
			carPrice.setTimeoutmoney(new Double(timeoutmoney));//超时费用
			carPrice.setOwnermoney(new Double(ownermoney));		//车主提成
			carPrice.setDiscount(new Double(discount));//会员折扣
			carDevice.setCarid(carid);
			carDevice.setDeviceid(deviceid);//设备编号
			carDevice.setSimcard(simcard);//sim卡号
			carDevice.setAddtime(new Date()); //添加时间
			
			int carShow = carsService.carShow(cars, carPrice, carDevice);
		}
		else{
			cars.setCarid(carid);
			cars.setCarstate(carstate);
			carsService.carShow(cars);
		}
	
		
		
		System.out.println(carid);
		return "1";

	}

	public void setCarsService(CarsService carsService) {
		this.carsService = carsService;
	}

}
